package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import bean.User;
import service.UserInfoService;

@WebServlet("/UserInfoServlet")
public class UserInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public UserInfoServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserInfoService service = new UserInfoService();
		String operation = request.getParameter("operation");
		String id = request.getParameter("id");
		String addressee = request.getParameter("addressee");
		String qq = request.getParameter("qq");
		String locked = request.getParameter("locked");
		String page = request.getParameter("page");
		String lock = request.getParameter("lock");
		String tel = request.getParameter("tel");
		String addr = request.getParameter("addr");
		
		if (operation != null) {
			switch(operation) {
			case "alt":
				User user = (User) request.getSession().getAttribute("user");
				if (service.getMapper().findByName(addressee) != null) {
					response.getWriter().write("{\"msg\":\"抱歉，收件人姓名被占用，请换一个！\"}");
					return;
				}
				service.alterUser(qq, addressee, tel, addr, user.getOpenid());
				user = service.getMapper().findByOpenid(user.getOpenid());
				request.getSession().setAttribute("user", user);
				response.getWriter().write("{\"msg\":\"成功\"}");
				break;
			case "getall":
				response.getWriter().write(service.getAllUser(addressee, qq, locked, page));
				break;
			case "del" :
				service.delUser(id);
				break;
			case "lock" :
				service.lockUser(id, lock);
				break;
			case "getbyid":
				User user2 = service.getMapper().findById(Integer.parseInt(id));
				response.getWriter().write(new Gson().toJson(user2));
				break;
			case "altbyid":
				User user3 = service.getMapper().findById(Integer.parseInt(id));
				if (service.getMapper().findByName(addressee) != null) {
					response.getWriter().write("{\"msg\":\"抱歉，收件人姓名被占用，请换一个！\"}");
					return;
				}
				service.alterUser(qq, addressee, tel, addr, user3.getOpenid());
				user = service.getMapper().findByOpenid(user3.getOpenid());
				request.getSession().setAttribute("user", user);
				response.getWriter().write("{\"msg\":\"成功\"}");
				break;
			}
		}else {
			User user = (User) request.getSession().getAttribute("user");
			response.getWriter().write(new Gson().toJson(user));
		}
	}
}